<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click.stop="isShow = true"
          >添加商户</el-button
        >
      </template>
      <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          @click="handleImport"
          >导入
        </el-button>
      </template>
      <!-- <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-delete"
          size="small"
          type="text"
          @click.stop="del(scope.row)"
          >删除</el-button
        >
      </template> -->
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page
          ref="searchOrgSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.orgNo"
          :url="website.searchLink.orgUrl"
          placeholder-text="机构"
          filter-key="searchParam"
        ></select-page>
      </template>
    </avue-crud>

    <el-dialog
      title="添加商户"
      :visible.sync="isShow"
      :close-on-click-modal="false"
      append-to-body
      @close="handleClose"
    >
      <avue-form
        ref="form"
        v-loading="loadingMer"
        :option="mercOption"
        v-model="mercForm"
        @submit="submitAdd"
      >
        <template slot-scope="{}" slot="rpiNo">
          <select-page
            ref="searchRpiSelect"
            label="rpiName"
            value="rpiNo"
            :select.sync="mercForm.rpiNo"
            :url="website.searchLink.merchantUrl"
            placeholder-text="商户"
            filter-key="searchParam"
          ></select-page>
        </template>
      </avue-form>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelFile">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :limit="1"
            :http-request="httpRequest"
            :on-change="handleChange"
            :on-remove="handleRemove"
            multiple
            :file-list="fileList"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              请上传 .xls,.xlsx 标准格式文件
            </div>
          </el-upload>
          <div style="display: flex; justify-content: flex-end">
            <el-button
              type="primary"
              @click="uploadSubmit"
              :disabled="uploadDisabled"
              v-show="fileList.length"
            >
              确定上传<i class="el-icon-upload2 el-icon--right"></i>
            </el-button>
          </div>
        </template>
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  addMerchant,
  remove,
  uploadFile,
  getExportTemplate,
} from "@/api/rb-oem/optimizemerchantrecord/optimize_info";
import { mapGetters } from "vuex";
import selectPage from "@/components/select-page/select-page";
import { downloadFileExcel } from "@/util/util";
export default {
  components: {
    selectPage,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      loadingMer: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        // menuWidth: 140, //操作栏宽度
        emptyBtnText: "重置",
        // searchIcon:true,
        // searchIndex:3,
        column: [
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: "select",
            searchOrder: 2,
            search: true,
            span: 24,
            overHidden: true,
            minWidth: 180,
            display: false,
          },
          {
            label: "",
            prop: "hasChild",
            type: "select",
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchType: "checkbox",
            searchSpan: 0,
            searchLabelWidth: "0",
            searchOrder: 2,
            dicData: [
              {
                label: "包含下级",
                value: 1,
              },
            ],
          },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: "input",
            minWidth: 180,
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: "select",
            search: true,
            overHidden: true,
            minWidth: 140,
            searchOrder: 3,
          },
          {
            label: "商户名称",
            prop: "rpiName",
            type: "input",
            minWidth: 180,
          },
          {
            label: "参与月份",
            prop: "merchantDate",
            type: "datetime",
            searchRange: true,
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
            search: true,
            // hide: true,
            display: false,
            searchSpan: 6,
            minWidth: 240,
          },
        ],
      },
      data: [],
      dataStatistics: {},
      isShow: false,
      mercForm: {
        id: "",
        rpiNo: "",
        merchantDate: "",
      },
      mercOption: {
        submitBtn: true,
        emptyBtn: false,
        column: [
          {
            label: "商户",
            prop: "rpiNo",
            type: "select",
            span: 24,
            rules: [
              {
                required: true,
                message: "请选择商户",
                trigger: "blur",
              },
            ],
          },
          {
            label: "参与月份",
            prop: "merchantDate",
            type: "month",
            // defaultTime: ['00:00:00', '23:59:59'],
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
            rules: [
              {
                required: true,
                message: "请选择参与月份",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      excelBox: false,
      excelForm: {
        merchantDate: "",
        excelFile: "",
        excelTemplate: "",
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "参与月份",
            prop: "merchantDate",
            type: "month",
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            startPlaceholder: "开始时间",
            endPlaceholder: "结束时间",
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            data: {
              merchantDate: "",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/optimizeMerchantInfo/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      uploadDisabled:false,
      fileList: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.paymentDetails_view, false),
        addBtn: this.vaildData(this.permission.paymentDetails_add, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  methods: {
    // 新增
    add(row) {
      this.mercForm.id = row.id;
      this.mercForm.serviceNo = row.serviceNo;
      this.isShow = true;
    },
    submitAdd(row, done, loading) {
      addMerchant(row).then(
        () => {
          this.onLoad(this.page, this.query);
          this.isShow = false;
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    handleClose() {
      this.mercForm = {
        id: "",
        rpiNo: "",
        merchantDate: "",
      };
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    uploadSubmit(){
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    httpRequest(option){
      this.uploadDisabled = true;
      this.excelBox = false;
      uploadFile(option.file, option.file.name, this.excelForm.merchantDate).then((res) => {
        this.uploadDisabled = false;
        this.$message({ type: "success", message: res.data.msg });
        this.refreshChange();
      },() =>{
        this.uploadDisabled = false;
      })
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      getExportTemplate().then(
        (res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    /**
     * @func edit,view 打开之前回调
     * @desc 点击获取点击天数时间
     * */
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    /**
     * @func 重置
     * @desc 重置查询条件
     * */
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    /**
     * @func 搜索
     * @desc 根据条件查询
     * @param {params} params --- 条件查询
     * */
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;

      let paramObj = Object.assign(params, this.query);
      if (!this.validatenull(paramObj.merchantDate)) {
        paramObj.beginTime = paramObj.merchantDate[0] || "";
        paramObj.endTime = paramObj.merchantDate[1] || "";
      }
      delete paramObj.merchantDate;

      getList(page.currentPage, page.pageSize, paramObj).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;

  .redFont {
    color: red;
  }
}

/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}

/deep/ .el-dialog__body {
  padding: 0 20px;
}
</style>